from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from .models import AIModel, ChatSession, ChatMessage, AIPromptTemplate
import json
import uuid
from datetime import datetime


def index(request):
    """主页 - 显示AI模型数量和基本信息"""
    total_models = AIModel.objects.count()
    active_models = AIModel.objects.filter(is_active=True).count()
    total_sessions = ChatSession.objects.count()
    total_messages = ChatMessage.objects.count()
    
    context = {
        'total_models': total_models,
        'active_models': active_models,
        'total_sessions': total_sessions,
        'total_messages': total_messages,
    }
    return render(request, 'admin/ai_app/dashboard.html', context)


def model_list(request):
    """模型列表页面"""
    models = AIModel.objects.all().order_by('-created_at')
    return render(request, 'admin/ai_app/model_list.html', {'models': models})


def session_list(request):
    """会话列表页面"""
    sessions = ChatSession.objects.all().order_by('-updated_at')[:50]
    return render(request, 'admin/ai_app/session_list.html', {'sessions': sessions})


@csrf_exempt
def test_ai(request):
    """测试AI功能的简单接口"""
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            message = data.get('message', '')
            model_id = data.get('model_id', 1)
            
            # 获取AI模型
            try:
                ai_model = AIModel.objects.get(id=model_id, is_active=True)
            except AIModel.DoesNotExist:
                return JsonResponse({'error': 'AI模型不存在或已禁用'}, status=400)
            
            # 模拟AI回复
            response = simulate_ai_response(message, ai_model)
            
            return JsonResponse({
                'success': True,
                'response': response,
                'model': ai_model.name
            })
            
        except Exception as e:
            return JsonResponse({'error': str(e)}, status=500)
    
    return JsonResponse({'error': '仅支持POST请求'}, status=405)


def simulate_ai_response(message, ai_model):
    """模拟AI回复功能"""
    # 这里可以集成真正的AI API
    responses = [
        f"你好！我是{ai_model.name}。关于你的问题\"{message}\"，这是一个很有趣的话题。",
        f"作为{ai_model.name}，我很高兴回答你的问题。对于\"{message}\"，我的理解是...",
        f"谢谢你使用{ai_model.name}。你提到的\"{message}\"让我想到了很多方面..."
    ]
    
    import random
    return random.choice(responses)
